package com.jiunuan.live.api.service.impl;

import com.jiunuan.live.account.interfaces.IAccountTokenRpc;
import com.jiunuan.live.api.service.IUserLoginService;
import com.jiunuan.live.api.vo.UserLoginVO;
import com.jiunuan.live.common.interfaces.utils.ConvertBeanUtils;
import com.jiunuan.live.common.interfaces.vo.WebResponseVO;
import com.jiunuan.live.msg.dto.MsgCheckDTO;
import com.jiunuan.live.msg.enums.MsgResultEnum;
import com.jiunuan.live.msg.interfaces.ISmsRpc;
import com.jiunuan.live.user.dto.UserLoginDTO;
import com.jiunuan.live.user.interfaces.IUserPhoneRpc;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import jakarta.servlet.http.Cookie;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

@Service
@Slf4j
public class UserLoginServiceImpl implements IUserLoginService {
    private static String PHONE_REG = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
    private static final Integer CODE_LENGTH = 4;
    @DubboReference
    private ISmsRpc smsRpc;
    @DubboReference
    private IUserPhoneRpc userPhoneRpc;
    @DubboReference
    private IAccountTokenRpc accountTokenRpc;

    /**
     * 发送登录验证码
     *
     * @param phone
     * @return
     */
    @Override
    public WebResponseVO sendLoginCode(String phone) {
        if(StringUtils.isEmpty(phone)){
            return WebResponseVO.errorParam("手机号不能为空");
        }
        if(!Pattern.matches(PHONE_REG, phone)){
            return WebResponseVO.errorParam("手机号格式异常");
        }
        MsgResultEnum msgResultEnum = smsRpc.sendLoginCode(phone);
        if(MsgResultEnum.SEND_SUCCESS.equals(msgResultEnum)){
            return WebResponseVO.success();
        }
        return WebResponseVO.sysError("短信发送太频繁，请稍后再试");
    }

    /**
     * 手机号+验证码登录
     *
     * @param phone
     * @param code
     * @param response
     * @return
     */
    @Override
    public WebResponseVO login(String phone, Integer code, HttpServletResponse response) {
        if(StringUtils.isEmpty(phone)){
            return WebResponseVO.errorParam("手机号不能为空");
        }
        if(!Pattern.matches(PHONE_REG, phone)){
            return WebResponseVO.errorParam("手机号格式异常");
        }
        if(code == null || code.toString().length() != CODE_LENGTH){
            return WebResponseVO.errorParam("验证码格式异常");
        }
        MsgCheckDTO msgCheckDTO = smsRpc.checkLoginCode(phone, code);
        if(!msgCheckDTO.isCheckStatus()){
            return WebResponseVO.bizError(msgCheckDTO.getDesc());
        }
        //验证码校验通过
        UserLoginDTO userLoginDTO = userPhoneRpc.login(phone);
        if(!userLoginDTO.isLoginSuccess()){
            log.error("用户登录失败，手机号：{}", phone);
            return WebResponseVO.sysError();
        }
        String token = accountTokenRpc.createAndSaveLoginToken(userLoginDTO.getUserId());
        Cookie cookie = new Cookie("JNTK", token);
        //设置顶级域名，接着我们的二级域名中进行web页面的访问，后续请求就会携带上它了
//        cookie.setDomain("qiyu.live.com");
        // 这里我们不设置域名，就设置为localhost
//        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(30 * 24 * 3600);
//        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addCookie(cookie);
        return WebResponseVO.success(ConvertBeanUtils.convert(userLoginDTO, UserLoginVO.class));
    }
}
